import AppConfig from '@/app.config'
import { getPageInfo, setTitle } from '@/path/acrossAPI'
import { BaseRouter } from '@/path/router'
import { toTabbarIndex } from '@/path/router/routers'
import { View } from '@tarojs/components'
import Taro from "@tarojs/taro"
import React, { useEffect, useState } from "react"
import imgBack from "@/static/images/back.png";
import imgAddress from "@/static/images/address.png";
import { XmImage } from '..'
import './index.scss'

function Index(props: { fixed?: boolean, color?: string, title?: string, menuBtn?: boolean, leftIcon?: string, hideLeftIcon?: boolean }) {
  const { statusBarHeight } = Taro.getSystemInfoSync()
  const menuButton = props.menuBtn ? Taro.getMenuButtonBoundingClientRect() : { top: 0 }
  const topBar = (statusBarHeight || 0) + menuButton.top
  const pageLength = getPageInfo().list.length
  const [isTabbar, setIsTabbar] = useState(false)
  const { fixed = true } = props
  function onBack() {
    if (pageLength > 1) {
      BaseRouter.back()
    } else {
      toTabbarIndex()
    }
  }
  useEffect(() => {
    if (props.title) {
      setTitle(props.title)
    }
  }, [props.title])
  useEffect(() => {
    const tabbarList = AppConfig.tabBar.list
    const _nowPage = getPageInfo()
    const _isTabbar = !!tabbarList.find(v => `/${v.pagePath}` === _nowPage.route)
    setIsTabbar(_isTabbar)
  }, [])
  return (
    <View className={`xm-navbar-box ${fixed ? 'xm-navbar-fixed' : ''}`} style={{ paddingTop: `${topBar}px` }}>
      {(!isTabbar || props.leftIcon) && !props.hideLeftIcon && <View className='xm-navbar-icon' onClick={onBack}>
        <XmImage src={props.leftIcon || (pageLength > 1 ? imgBack : imgAddress)} size={48} />
      </View>}
      {props.title ? <View className='xm-navbar-title s-lg-1 f-weight-bold' style={{ color: props.color }}>{props.title}</View> : null}
    </View>
  )
}
export default React.memo(Index)
